package visual;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import data.MatrixTime;
import utils.kml.*;


public class GHeat {
	private static String COLORSCHEME = "fire";
	private static String LEGENDURL = "http://pervasive2.morselli.unimo.it/~laura/images/"+COLORSCHEME+".png";
	
	public static void printMap(List<MatrixTime> erlang_times, String out_dir) {
		try {
			
			new File(out_dir+"/imgs/").mkdir();
			
			Kml utilsKml = new Kml();
			
			PrintWriter out = new PrintWriter(new FileWriter(new File(out_dir+"heat.kml")));
			utilsKml.printHeaderFolder(out, out_dir.substring(out_dir.indexOf("/")+1));
		
			
			for(int i=0; i<erlang_times.size();i++) {
				MatrixTime et = erlang_times.get(i);
				printMap(et,erlang_times,i,out_dir+"/imgs/",out);
			}
			
			//print colorscheme legend
			Kml k = new Kml();
			k.printScreenOverlayLowerRight(out, LEGENDURL, COLORSCHEME);
			
			utilsKml.printFooterFolder(out);
			out.close();
			
			System.out.println("Starting Python at "+new File(out_dir+"/imgs/").getAbsolutePath());
			Process p=Runtime.getRuntime().exec("heatmap-1.0/gheat.bat "+new File(out_dir+"/imgs/").getAbsolutePath()+" "+100); 
			BufferedReader br_err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
			BufferedReader br_out = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = br_out.readLine()) != null) 
				System.out.println(line);
			
			while ((line = br_err.readLine()) != null) 
				System.err.println(line);
			
			p.waitFor(); 
			
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
	
	private static void printMap(MatrixTime mt, List<MatrixTime> erlang_times, int index, String dir, PrintWriter out) throws Exception {
		
		
		// crate the file with the points to be passed to gheat
		
		double[][] bbox = mt.getArea().getBBox();
		double min_x = bbox[0][0];
		double min_y = bbox[0][1];
		double max_x = bbox[1][0];
		double max_y = bbox[1][1];
		
		/*
		double min_x = Double.MAX_VALUE;
		double min_y = Double.MAX_VALUE;
		double max_x = Double.MIN_VALUE;
		double max_y = Double.MIN_VALUE;
		*/
		
		
		File f = new File(dir+index+".txt");
		PrintWriter out_txt = new PrintWriter(new FileWriter(f));
	
		// enter the border points
		
		out_txt.println(min_x+","+min_y);
		out_txt.println(max_x+","+max_y);
		
		
		int how_many_points = 0;
		for(int i=0; i<mt.getMat().length;i++)
		for(int j=0; j<mt.getMat()[i].length;j++) {
			double[] center = mt.getArea().getCenter(i, j);
			double val = mt.getVal(i, j);
			int n_points = (int)(val * 10.0);
			if(n_points < 4) n_points=0;
			
			
			double noise = 0.001;
			double x,y;
			for(int k=0; k<n_points;k++) {
				how_many_points ++;
				x = center[0] + noise*(0.5 - Math.random());
				y = center[1] + noise*(0.5 - Math.random());
				min_x = Math.min(min_x, x);
				min_y = Math.min(min_y, y);
				max_x = Math.max(max_x, x);
				max_y = Math.max(max_y, y);
				out_txt.println(x+","+y);
			}
		}
		out_txt.close();
		
		if(how_many_points < 2)
			f.delete();
		
		// compile the main kml accordingly
		out.println("<Folder>");
		out.println("<name>"+FORMATTER.format(mt.getStart().getTime())+"-"+FORMATTER.format(mt.getEnd().getTime())+"</name>");
		out.println("<TimeSpan>");
		out.println("<begin>"+FORMATTER.format(mt.getStart().getTime())+"</begin>");
		out.println("<end>"+FORMATTER.format(mt.getEnd().getTime())+"</end>");
		out.println("</TimeSpan>");
		
		
		if(how_many_points >= 2) {
			out.println("<GroundOverlay>");
			out.println("<Icon>");
			out.println("<href>imgs/"+index+".png</href>");
			out.println("</Icon>");
			out.println("<LatLonBox>");
			out.println("<north>"+max_y+"</north>");
			out.println("<south>"+min_y+"</south>");
			out.println("<east>"+max_x+"</east>");
			out.println("<west>"+min_x+"</west>");
			out.println("<rotation>0</rotation>");
			out.println("</LatLonBox>");
			out.println("</GroundOverlay>");
		}
		out.println("</Folder>");
	}
}
